在前五篇,我們建構了完整的內容生成系統,今天我們要探討智能助手的「檔案處理入口」:檔案上傳系統。
這個系統能夠處理多種格式的檔案,通過本地 API 服務實現強大的檔案解析能力,並建立完整的狀態管理機制為後續的智能分析做準備。
檔案上傳系統提供:
def upload_file_tool(self, file_path: str) -> str:
"""上傳檔案並分兩階段處理"""
print(f"[DEBUG] ===== upload_file_tool 被調用了! =====")
print(f"[DEBUG] 檔案路徑: '{file_path}'")
try:
if not file_path or not Path(file_path).exists():
return "檔案路徑無效或檔案不存在"
filename = Path(file_path).name
print(f"[DEBUG] 準備上傳檔案: {filename}")
with open(file_path, 'rb') as file:
files = {'file': (filename, file, 'application/octet-stream')}
print(f"[DEBUG] 發送請求到API...")
response = requests.post(f"{LOCAL_API_BASE}/upload-file", files=files, timeout=30)
print(f"[DEBUG] API響應狀態碼: {response.status_code}")
print(f"[DEBUG] API響應內容: {response.text[:200]}...")
response.raise_for_status()
result = response.json()
if result['status'] == 'success':
# 儲存檔案內容供後續使用(統一變數名稱)
if self.app_instance:
import time
self.app_instance.last_uploaded_file_content = result['content']
self.app_instance.uploaded_file_content = result['content'] # 統一變數名稱
self.app_instance.last_uploaded_filename = filename
self.app_instance.last_upload_time = time.time()
print(f"[DEBUG] 已保存上傳檔案內容,長度: {len(result['content'])},時間戳: {self.app_instance.last_upload_time}")
# 設置等待用戶回覆的標記
self.app_instance.waiting_for_file_action = True
return f"""✅ 檔案上傳成功!
📁 檔案名稱: {filename}
📊 檔案大小: {len(result['content'])} 字元
📝 檔案類型: {Path(filename).suffix or '未知'}
請問您想要做什麼?
• 分析重點 - 找出檔案中的關鍵信息
• 解題 - 解答檔案中的問題
• 寫心得 - 根據檔案內容寫感想
• 翻譯 - 翻譯檔案內容
• 總結 - 提供內容摘要
• 詳細分析 - 深入分析檔案內容
請直接告訴我您的需求!"""
else:
return f"檔案上傳失敗: {result['message']}"
except requests.exceptions.ConnectionError:
return "錯誤:無法連線到本地 API 服務。請確認伺服器已啟動。"
except Exception as e:
return f"檔案上傳時發生錯誤: {e}"
if not file_path or not Path(file_path).exists():
return "檔案路徑無效或檔案不存在"
filename = Path(file_path).name
print(f"[DEBUG] 準備上傳檔案: {filename}")
with open(file_path, 'rb') as file:
files = {'file': (filename, file, 'application/octet-stream')}
print(f"[DEBUG] 發送請求到API...")
response = requests.post(f"{LOCAL_API_BASE}/upload-file", files=files, timeout=30)
print(f"[DEBUG] API響應狀態碼: {response.status_code}")
print(f"[DEBUG] API響應內容: {response.text[:200]}...")
response.raise_for_status()
result = response.json()
if result['status'] == 'success':
if self.app_instance:
import time
self.app_instance.last_uploaded_file_content = result['content']
self.app_instance.uploaded_file_content = result['content'] # 統一變數名稱
self.app_instance.last_uploaded_filename = filename
self.app_instance.last_upload_time = time.time()
print(f"[DEBUG] 已保存上傳檔案內容,長度: {len(result['content'])},時間戳: {self.app_instance.last_upload_time}")
# 設置等待用戶回覆的標記
self.app_instance.waiting_for_file_action = True
狀態管理特色:
last_uploaded_file_content
:最新上傳的檔案內容uploaded_file_content
:統一變數名稱確保相容性last_uploaded_filename
:保存原始檔案名稱last_upload_time
:精確記錄上傳時間戳waiting_for_file_action
:設定為 True
表示等待用戶指令LOCAL_API_BASE = os.environ.get("LOCAL_API_BASE", "http://127.0.0.1:8000")
配置特色:
response = requests.post(f"{LOCAL_API_BASE}/upload-file", files=files, timeout=30)
對接特色:
/upload-file
專門處理檔案上傳except requests.exceptions.ConnectionError:
return "錯誤:無法連線到本地 API 服務。請確認伺服器已啟動。"
except Exception as e:
return f"檔案上傳時發生錯誤: {e}"
錯誤處理特色:
return f"""✅ 檔案上傳成功!
📁 檔案名稱: {filename}
📊 檔案大小: {len(result['content'])} 字元
📝 檔案類型: {Path(filename).suffix or '未知'}
請問您想要做什麼?
• 分析重點 - 找出檔案中的關鍵信息
• 解題 - 解答檔案中的問題
• 寫心得 - 根據檔案內容寫感想
• 翻譯 - 翻譯檔案內容
• 總結 - 提供內容摘要
• 詳細分析 - 深入分析檔案內容
請直接告訴我您的需求!"""
用戶體驗特色:
# 檔案大小監控
print(f"[DEBUG] 已保存上傳檔案內容,長度: {len(result['content'])}")
# 超時控制
response = requests.post(f"{LOCAL_API_BASE}/upload-file", files=files, timeout=30)
# 記憶體管理
# 檔案內容保存到實例變數而非全域變數
# 檔案存在性檢查
if not file_path or not Path(file_path).exists():
return "檔案路徑無效或檔案不存在"
# 錯誤資訊控制
except Exception as e:
return f"檔案上傳時發生錯誤: {e}" # 不洩露敏感系統資訊
檔案上傳系統是智能助手的「資料入口閘道」,它:
這個系統為後續的智能分析奠定了堅實的基礎,讓 AI 助手能夠理解和處理用戶提供的各種文件資料。
下一篇,我們將深入探討六大專家分析系統,看看 AI 如何根據不同的專業領域提供深度分析服務。